/**
 * Module dependencies.
 */

var express = require('express'), routes = require('./routes'), userManager = require('./routes/userManager');
var socketIO = require('socket.io');
var app = module.exports = express.createServer();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

app.configure(function() {
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
		secret : "keyboard cat"
	}));
	app.use(app.router);
	app.use(express.static(__dirname + '/public'));
});

app.configure('development', function() {
	app.use(express.errorHandler({
		dumpExceptions : true,
		showStack : true
	}));
});

app.configure('production', function() {
	app.use(express.errorHandler());
});
// Routes

app.get('/index', routes.index);
app.get('/registerUserForm', routes.registerUserForm);
app.get('/', routes.loginUserForm);
app.get('/loginUserForm', routes.loginUserForm);

app.get('/libs/*', routes.sendFiles);
app.get('/public/*', routes.sendFiles);
app.get('/representation/*', routes.sendFiles);
app.get('/shapes/*', routes.sendFiles);
app.get('/Styles/*', routes.sendFilesNoSession);
app.get('/userStageActions/*', routes.sendFiles);

app.post('/registerUser', userManager.registerNewUser);
app.post('/loginUser', userManager.loginUser);
app.post('/saveModels', userManager.saveModels);
app.post('/loadModels', userManager.loadModels);
app.post('/getUserName', userManager.getUserName);

app.listen(3000, function() {
	console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
var SharedModel = new Schema({
	model : {}
});
//var CommandModel = conn.model('SharedModel2', SharedModel);

var webSocket = socketIO.listen(app, {
	log : false
});
// socketIO.set('log level', 1);
// var commandModel = new CommandModel();
// commandModel.model = {};
// commandModel.save();
// CommandModel.find({}, function(err, docs) {
// console.log("number of docs is: " + docs.length);
// console.log(docs[0].model);
// });
var seqNumber = 0;
var commands = [];
var userTracker = {};
var conn = mongoose.createConnection('mongodb://localhost/UMLDB');

var commandSchema = new Schema({
	json : {
	}
});

var userTrackerSchema = new Schema({
	userName : String,
	command : Number

});
var Commands = conn.model('Command', commandSchema);
var UserTracker = conn.model('UserTracker', userTrackerSchema);
Commands.find({}).remove();
UserTracker.find({}).remove();
webSocket.sockets.on('connection', function(client) {
	// client.emit('commands',{cmds:commands});
	console.log("client " + client + " has reconnected");

	client.on('intent', function(message) {
		webSocket.sockets.emit("intent", message);
	});

	client.on('getCommands', function(message) {
		Commands.find({})
		//.sort('json.seqNumber')
		.exec(function(err, docs) {
			var count = docs.length;
			var i = 0;
			var cmds = []
			for( i = 0; i < count; i++) {
				cmds[i] = docs[i].json;
			}

			if(count == 0) {
				console.log("No Commands found");
				client.emit('commands', {
					cmds : cmds,
					lastExecutedCommand : -1
				});
			} else {
				UserTracker.find({
					'userName' : message.userName
				}, function(err, docs2) {
					var count = docs2.length;
					if(count != 0) {
						console.log(docs2[0].userName + " asked for commands with last executed Command " + docs2[0].command);
						client.emit('commands', {
							cmds : cmds,
							lastExecutedCommand : docs2[0].command
						});
					} else {
						client.emit('commands', {
							cmds : cmds,
							lastExecutedCommand : -1
						});
					}

					console.log(docs.length + " commands found");
				});
			}
		});
		// client.emit('commands', {
		// cmds : commands,
		// lastExecutedCommand : userTracker[message.userName]
		// });
	});

	client.on('setLastExecutedCommand', function(message) {
		UserTracker.find({
			'userName' : message.userName
		}, function(err, docs) {
			var count = docs.length;
			if(count != 0) {
				console.log("last executed command from " + docs[0].userName + " is " + docs[0].command);
				if(docs[0].command < message.lastExecutedCommand) {
					docs[0].command = message.lastExecutedCommand;
				}
				docs[0].save();
				console.log("updated");
			} else {
				var tracker = new UserTracker();
				tracker.userName = message.userName;
				tracker.command = message.lastExecutedCommand
				tracker.save();
			}
		});
		// userTracker[message.userName] = message.lastExecutedCommand;
		// console.log("last executed command from client " + message.userName + " is " + message.lastExecutedCommand);
	});

	client.on('currentModel', function(message) {
		console.log("currentModel  from " + message.userName);
	});
	client.on('currentView', function(message) {
		console.log("currentView from " + message.userName);
	});
	client.on('command', function(message) {

		// CommandModel.find({}, function(err, docs) {
		// var cmds;
		// if(docs[0].model) {
		// console.log("model is defined");
		// console.log(docs[0]);
		// console.log(docs[0].model.commands[0]);
		// if(docs[0].model.commands) {
		// console.log("commands is defined");
		// docs[0].model.commands.push(message);
		// console.log(message);
		// console.log(docs[0].model.commands);
		// docs[0].save(function(err){
		// console.log("saving");
		// if(err)
		// {
		// console.log("error + "+ err);
		// }
		// });
		// } else {
		// console.log("commands is not defined");
		// cmds = [message];
		// docs[0].model = {
		// commands : cmds
		// }
		// }
		//
		// } else {
		// console.log("model is not defined");
		// docs[0].model = {
		// commands : [message]
		// }
		// }
		//
		// // docs[0].save();
		//
		// CommandModel.find({}, function(err, docs) {
		// console.log(docs[0].model.commands.length);
		// });
		// });

		Commands.find({}, function(err, docs) {
			console.log(message);
			var count = docs.length;
			var command = new Commands();
			command.json = message;
			command.json.seqNumber = count;
			command.save();
			if(message.name == "moveClass") {
				client.broadcast.emit("command", command.json);
			} else {
				webSocket.sockets.emit("command", command.json);
			}
		});
		// message.seqNumber = seqNumber++;
		// commands[commands.length] = message;
		// if(message.name == "moveClass") {
			// client.broadcast.emit("command", message);
		// } else {
			// webSocket.sockets.emit("command", message);
		// }

		// client.emit("command",message);

	});

	client.on('disconnect', function() {
		// var broadcastMessage = userName + ' has left the zone.';
		// client.broadcast.send(broadcastMessage);
		// client.send(broadcastMessage);
		console.log(client + " has disconnected");
	});
});
